package com.hqd.ch03.v39.reader.support;

import com.hqd.ch03.v39.io.Resource;
import com.hqd.ch03.v39.reader.BeanDefinitionReader;
import com.hqd.ch03.v39.reader.xml.doc.DocumentLoader;
import com.hqd.ch03.v39.reader.xml.doc.support.DefaultDocumentLoader;
import com.hqd.ch03.v39.reader.xml.error.SimpleSaxErrorHandler;
import com.hqd.ch03.v39.reader.xml.parse.BeanDefinitionDocumentReader;
import com.hqd.ch03.v39.reader.xml.parse.spport.DefaultBeanDefinitionDocumentReader;
import com.hqd.ch03.v39.reader.xml.resolver.ResourceEntityResolver;
import com.hqd.ch03.v39.registry.BeanDefinitionRegistry;
import org.w3c.dom.Document;

public class XmlBeanDefinitionReader implements BeanDefinitionReader {
    private final BeanDefinitionRegistry beanDefinitionRegistry;
    private DocumentLoader documentLoader = new DefaultDocumentLoader();
    private BeanDefinitionDocumentReader documentReader = new DefaultBeanDefinitionDocumentReader();

    public XmlBeanDefinitionReader(BeanDefinitionRegistry beanDefinitionRegistry) {
        this.beanDefinitionRegistry = beanDefinitionRegistry;
    }


    @Override
    public void loadBeanDefinition(Resource resource) {
        Document doc = documentLoader.loadDocument(resource, new ResourceEntityResolver(), new SimpleSaxErrorHandler());
        registerBeanDefinitions(doc);
    }

    private void registerBeanDefinitions(Document doc) {
        this.documentReader.registerBeanDefinitions(doc, beanDefinitionRegistry);
    }

    public void setDocumentLoader(DocumentLoader documentLoader) {
        this.documentLoader = (documentLoader != null ? documentLoader : new DefaultDocumentLoader());
    }

    public void setDocumentReader(BeanDefinitionDocumentReader documentReader) {
        this.documentReader = documentReader;
    }
}
